# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)
_GATEWAY = 'http://jspay.wiipay.cn/1/jspay/qq/qq_api.do'
_ALI_GATEWAY = 'http://jspay.wiipay.cn/1/jspay/ali/ali_api.do'

APP_CONF = {
    '832378399f57132ec040e113b3558043': {
        'API_KEY': '09iy4dgo6374twzluntigc2usgzh6b6v',
    },
    'a9df715c6c9614a5813615d478861213': {
        'API_KEY': 'dw7aryyatuio396da1pz5du92rhle5lf',
    },
    '7f7269e6f640a2b89507bbf83157666d': {
        'API_KEY': '09iy4dgo6374twzluntigc2usgzh6b6v',
    },
    'addcda6e257cb1486ffa039c1e34b929': {  # loki qq
        'API_KEY': 'dhj35nidi3fejocljp33lm7k97kym287',
    },
    'd09187c9e384cacb90fabb100dc8f2c8': {  # loki 支付宝
        'API_KEY': 'dhj35nidi3fejocljp33lm7k97kym287',
    },
    '9c93f8186365f1e911f9d4eb348de933': {  # dwc qq
        'API_KEY': 'njc5inxq8a1mvzsbzvjeqif01pwtbq8z',
    },
    '9bae404e409f37205ebf80213888c6cd': {  # dwc 支付宝
        'API_KEY': 'njc5inxq8a1mvzsbzvjeqif01pwtbq8z',
    },
    'd3b41196c5edf8a72dd6db92b23f7c48': {  # dbl
        'API_KEY': 'l66q2l12uwaxpd04jsm0037fe5wu3rgl',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] != '' and parameter[k] != None:
            s += '%s=%s&' % (k, parameter[k])
    s = s[0: len(s) - 1]
    s += key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("weipaipay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    service = info['service']
    if service == 'alipay':
        return create_ali_charge(pay, pay_amount, info)

    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('version', '2.0'),
        ('format', 'json'),
        ('body', 'charge'),
        ('total_fee', str(pay_amount)),
        ('app_id', app_id),
        ('out_trade_no', str(pay.id)),
        ('callback_url', '{}/pay/api/{}/weipaipay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, app_id)),
        ('user_ip', _get_device_ip(info)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("weipaipay create charge data: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['out_trade_no'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("weipaipay create rsp: %s %s",
                 response.status_code, response.text)
    res_obj = json.loads(response.text)
    return {'charge_info': res_obj['pay_url']}


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_ali_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('version', '2.0'),
        ('format', 'json'),
        ('body', 'charge'),
        ('total_fee', str(pay_amount)),
        ('app_id', app_id),
        ('out_trade_no', str(pay.id)),
        ('callback_url', '{}/pay/api/{}/weipaipay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, app_id)),
        ('user_ip', _get_device_ip(info)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("weipaipay create charge data: %s ", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_ALI_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("weipaipay ali create rsp: %s %s", response.status_code, response.text)
    res_obj = json.loads(response.text)
    return {'charge_info': res_obj['pay_url']}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("weipaipay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['cpparam']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('weipaipay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data['status']
    trade_no = data['orderNo']
    total_fee = float(data['price'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 'success':
        _LOGGER.info('weipaipay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_id, mer_id=None, trade_no=None):
    ''' 未提供查询订单 '''
    pass
